#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <syscall.h>
// c++11底层封装的pthread原生库
//  线程的局部存储！有什么用？(获取自己线程的各种属性) 有什么坑？
// int g_val = 10;
__thread int g_val = 10; //编译时选项，可以让每一个线程都有一份

__thread pid_t lwp;

// __thread std::string name;

pid_t gettid()
{
    return syscall(SYS_gettid);
}

void *ThreadRoutine(void *arg)
{
    lwp = gettid();
    std::string threadname = static_cast<const char *>(arg);
    while (true)
    {
        g_val++;
        std::cout << threadname << ", g_val : " << g_val << " &g_val : " << &g_val << std::endl
                  << std::endl;
        std::cout << "new thread lwp : " << lwp << std::endl;
        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, ThreadRoutine, (void *)"thraed 1");
    lwp = gettid();
    while (true)
    {
        std::cout << "main thread , g_val : " << g_val << " &g_val : " << &g_val << std::endl
                  << std::endl;
        std::cout << "main thread lwp : " << lwp << std::endl;
        sleep(1);
    }
    return 0;
}

// void myrun()
// {
//     while (true)
//     {
//         std::cout << "I am a thread " << std::endl;
//         sleep(1);
//     }
// }

// int main()
// {
//     std::thread t(myrun);

//     t.join();
//     return 0;
// }